<?php

namespace app\adminapi\service;

use app\adminapi\model\sysdict\SysDictDataDO;
use app\adminapi\model\sysdict\SysDictTypeDO;
use app\common\exception\OtherException;

class SysDictTypeService
{
    public function list(array $param)
    {
        $where = [];
        if (isset($param['dictName'])) {
            $where[] = ['dict_name', 'like', '%' . $param['dictName'] . '%'];
        }
        if (isset($param['dictCode'])) {
            $where[] = ['dict_code', 'like', '%' . $param['dictCode'] . '%'];
        }
        if (isset($param['timeArr'])) {
            $where[] = ['create_time', 'between', $param['timeArr']];
        }
        $paginate['list_rows'] = $param['pageSize'];
        if (isset($param['pageNo'])) {
            $paginate['page'] = $param['pageNo'];
        }
        $result = (new SysDictTypeDO())
            ->where($where)
            ->paginate($paginate)
            ->toArray();
        return [
            'total' => $result['total'],
            'list' => $result['data']
        ];
    }

    public function addSysDictType(array $sysDictTypeDO)
    {
        $this->validDictCodeExist($sysDictTypeDO['dictCode'],null);
        return SysDictTypeDO::create($sysDictTypeDO);
    }

    public function deleteSysDictType(int $dictId)
    {
        $this->validDictTypeExist($dictId);
        // 查询字典数据
        $model = SysDictTypeDO::find($dictId);
        $where['dict_type'] = $model['dictCode'];
        // 删除数据字典和字典数据
        $model->startTrans();
        try {
            SysDictDataDO::destroy($where);
            $model->delete();
            $model->commit();
            return 1;
        }catch (\Exception $e){
            $model->rollback();
            throw new OtherException($e->getMessage());
        }
    }

    public function updateSysDictType(array $sysDictTypeDO)
    {
        $this->validDictTypeExist($sysDictTypeDO['dictId']);
        $this->validDictCodeExist($sysDictTypeDO['dictCode'],$sysDictTypeDO);
        return SysDictTypeDO::update($sysDictTypeDO);
    }

    public function getSysDictType(int $dictId)
    {
        $this->validDictTypeExist($dictId);
        return SysDictTypeDO::find($dictId);
    }

    private function validDictTypeExist(int $dictId)
    {
        $exist = SysDictTypeDO::find($dictId);
        if ($exist == null) {
            throw new OtherException('字典类型不存在');
        }
    }

    private function validDictCodeExist(string $newDictCode, $sysDictTypeDO)
    {
        $where[] = ['dict_code', '=', $newDictCode];
        $exist = (new SysDictTypeDO())->where($where)->find();
        if ($exist) {
            if ($sysDictTypeDO !== null) {
                if ($exist['dictId'] !== $sysDictTypeDO['dictId']) {
                    throw new OtherException('字典类型编码已存在');
                }
            } else {
                throw new OtherException('字典类型编码已存在');
            }
        }
    }
}